<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>设备管理</title>
    <link rel="stylesheet" href="./css/styles.css">
    <link rel="stylesheet" href="./css/device-info.css">
    <script src="./scripts/spark-md5.min.js"></script>
</head>
<body>

<div class="sidebar">
    <a onclick="showPage('device-info')">设备信息</a>
    <a onclick="showPage('device-config')">设备配置</a>
    <a onclick="showPage('upgrade')">固件升级</a>
    <a onclick="showPage('video')">视频播放</a>
    <a onclick="showPage('logs')">日志查询</a>
</div>

<div class="content">
    <!-- 设备信息页面 -->
    <div id="device-info" class="page">
        <h2>设备信息</h2>
        <button id="fetch-info-btn" class="refresh-btn">获取设备信息</button>

        <div class="device-info-container">
            <!-- 设备信息卡片 -->
            <div class="info-card device-info">
                <h3>设备信息</h3>
                <div class="info-item">
                    <span class="info-label">设备型号:</span>
                    <span class="info-value" id="device-model">--</span>
                </div>
                <div class="info-item">
                    <span class="info-label">SN码:</span>
                    <span class="info-value" id="device-sn">--</span>
                </div>
            </div>

            <!-- 版本信息卡片 -->
            <div class="info-card version-info">
                <h3>版本信息</h3>
                <div class="info-item">
                    <span class="info-label">硬件版本:</span>
                    <span class="info-value" id="hardware-version">--</span>
                </div>
                <div class="info-item">
                    <span class="info-label">OEM版本:</span>
                    <span class="info-value" id="oem-version">--</span>
                </div>
                <div class="info-item">
                    <span class="info-label">固件版本:</span>
                    <span class="info-value" id="firmware-version">--</span>
                </div>
                <div class="info-item">
                    <span class="info-label">SDK版本:</span>
                    <span class="info-value" id="sdk-version">--</span>
                </div>
                <div class="info-item">
                    <span class="info-label">软件版本:</span>
                    <span class="info-value" id="software-version">--</span>
                </div>
                <div class="info-item">
                    <span class="info-label">OTA版本:</span>
                    <span class="info-value" id="ota-version">--</span>
                </div>
            </div>

            <!-- 系统状态卡片 -->
            <div class="info-card system-status">
                <h3>系统状态</h3>
                <div class="info-item">
                    <span class="info-label">存储空间:</span>
                    <span class="info-value" id="storage-space">--</span>
                </div>
            </div>
        </div>

        <!-- 原始JSON显示区域（可选，用于调试） -->
        <div style="margin-top: 30px;">
            <details>
                <summary style="cursor: pointer; padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 10px;">查看原始数据</summary>
                <pre id="info-display" style="margin-top: 10px;"></pre>
            </details>
        </div>
    </div>

    <!-- 设备配置页面 -->
    <div id="device-config" class="page">
        <h2>设备配置</h2>
        <div class="config-tabs">
            <div class="config-tab active" onclick="showConfigSection('param-config')">参数配置</div>
            <div class="config-tab" onclick="showConfigSection('system-config')">系统设置</div>
        </div>

        <!-- 参数配置页面 -->
        <div id="param-config" class="config-content active">
            <div class="config-form">
                <h3>基本信息设置</h3>
                
                <!-- SN码设置 -->
                <div class="form-group">
                    <label for="sn-input">SN码:</label>
                    <input type="text" id="sn-input" placeholder="请输入SN码">
                </div>
                
                <!-- 设备型号设置 -->
                <div class="form-group">
                    <label for="model-input">设备型号:</label>
                    <input type="text" id="model-input" placeholder="请输入设备型号" readonly>
                </div>
                
                <!-- 硬件版本设置 -->
                <div class="form-group">
                    <label for="hw-version-input">硬件版本:</label>
                    <input type="text" id="hw-version-input" placeholder="请输入硬件版本号">
                </div>
                
                <!-- OEM版本设置 -->
                <div class="form-group">
                    <label for="oem-version-input">OEM版本:</label>
                    <input type="text" id="oem-version-input" placeholder="请输入OEM版本号">
                </div>
                
                <div class="form-actions">
                    <button id="get-current-info-btn" class="btn-sync">获取当前设备信息</button>
                    <button id="save-device-info-btn" class="btn-save">保存设备信息</button>
                </div>
                <p id="device-info-status"></p>
            </div>
        </div>

        <!-- 系统设置页面 -->
        <div id="system-config" class="config-content">
            <div class="config-form">
                <h3>时间同步</h3>
                <div class="form-group">
                    <label>当前系统时间:</label>
                    <div id="current-time" style="padding: 8px; background-color: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px;">--</div>
                </div>
                <div class="form-actions">
                    <button id="sync-time-btn" class="btn-sync">同步当前系统时间到设备</button>
                </div>
                <p id="time-sync-status"></p>
            </div>

            <div class="config-form">
                <h3>系统操作</h3>
                <div class="form-group">
                    <label>系统重启:</label>
                    <p style="color: #666; font-size: 14px;">重启设备以应用新的配置</p>
                </div>
                <div class="form-actions">
                    <button id="reboot-btn" class="btn-save" style="background-color: #dc3545;" onmouseover="this.style.backgroundColor='#c82333'" onmouseout="this.style.backgroundColor='#dc3545'">重启设备</button>
                </div>
                <p id="reboot-status"></p>
            </div>

            <div class="config-form">
                <h3>恢复出厂设置</h3>
                <div class="form-group">
                    <label>恢复默认配置:</label>
                    <p style="color: #666; font-size: 14px;">将设备配置恢复到出厂默认状态</p>
                </div>
                <div class="form-actions">
                    <button id="factory-reset-btn" class="btn-save" style="background-color: #dc3545; color: white;" onmouseover="this.style.backgroundColor='#c82333'" onmouseout="this.style.backgroundColor='#dc3545'">恢复出厂设置</button>
                </div>
                <p id="factory-reset-status"></p>
            </div>
        </div>
    </div>

    <!-- 固件升级页面 -->
    <div id="upgrade" class="page">
        <h2>固件升级</h2>
        <label for="file-input">选择固件文件:</label><br>
        <input type="file" id="file-input"><br>
        <button id="start-upgrade-btn">开始升级</button>
        <div id="upgrade-progress"></div>
        <p id="upgrade-status"></p>
    </div>

    <!-- 视频播放页面 -->
    <div id="video" class="page">
        <h2>视频播放</h2>
        <div id="video-container">
            <p>RTSP流地址: rtsp://localhost:554/live/track0</p>
            <p>(浏览器通常不直接支持RTSP流，需要后端转码或使用专用播放器/插件)</p>
        </div>
    </div>

    <!-- 日志查询页面 -->
    <div id="logs" class="page">
        <h2>日志查询</h2>
        <div class="log-controls" style="margin-bottom: 15px; display: flex; align-items: center; gap: 10px;">
            <label for="log-level" style="white-space: nowrap;">日志等级:</label>
            <select id="log-level" style="padding: 5px; width: 100px; flex-shrink: 0;">
                <option value="all">全部</option>
                <option value="info">Info</option>
                <option value="warning">Warning</option>
                <option value="error">Error</option>
                <option value="debug">Debug</option>
                <option value="trace">Trace</option>
                <option value="critical">Critical</option>
            </select>
            <button id="fetch-logs-btn" class="refresh-btn" style="font-size: 14px; padding: 8px 15px;">刷新日志</button>
            <button id="export-logs-btn" class="btn-save" style="background-color: #28a745; margin-left: auto;">导出日志</button>
        </div>
        <div id="log-display" style="background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 15px; min-height: 300px; max-height: 600px; overflow-y: auto;">
            <pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0;">请点击“刷新日志”以获取最新日志。</pre>
        </div>
    </div>
</div>

<script>
    // 页面切换逻辑
    const pages = document.querySelectorAll('.page');
    const sidebarLinks = document.querySelectorAll('.sidebar a');

    // 声明自动刷新相关变量
    let autoRefreshInterval;

    function showPage(pageId) {
        pages.forEach(page => {
            page.classList.remove('active');
        });
        document.getElementById(pageId).classList.add('active');

        sidebarLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('onclick').includes(pageId)) {
                link.classList.add('active');
            }
        });

        // 如果切换到设备信息页面，自动触发查询设备信息
        if (pageId === 'device-info') {
            // 显示加载状态并获取设备信息
            showLoadingState();
            fetchDeviceInfo();
            // startAutoRefresh();
        } else if (pageId === 'device-config') {
            // 切换到设备配置页面时，自动获取设备信息并填充表单
            autoLoadDeviceInfoToForm();
        } else if (pageId === 'logs') {
            fetchLogs();
        }
        else {
            // 切换到其他页面时停止自动刷新
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
            }
        }
    }

    // 默认显示设备信息页面
    showPage('device-info');

    // 设备信息逻辑
    document.getElementById('fetch-info-btn').addEventListener('click', () => {
        // 显示加载状态
        showLoadingState();
        fetchDeviceInfo();
    });

    // 获取设备信息的通用函数
    function fetchDeviceInfo() {
        const infoDisplay = document.getElementById('info-display');

        fetch('/api/info')
            .then(response => response.json())
            .then(data => {
                // 更新原始数据显示
                infoDisplay.textContent = JSON.stringify(data, null, 2);

                // 更新设备信息卡片
                updateDeviceInfo(data);
                updateVersionInfo(data);
                updateSystemStatus(data);
            })
            .catch(error => {
                console.error('获取设备信息失败:', error);
                // 在错误时显示错误状态
                showErrorState();
            });
    }

    // 显示加载状态
    function showLoadingState() {
        const allValues = document.querySelectorAll('.info-value');
        allValues.forEach(element => {
            element.textContent = '加载中...';
            element.className = 'info-value loading';
        });
    }

    // 显示错误状态
    function showErrorState() {
        const allValues = document.querySelectorAll('.info-value');
        allValues.forEach(element => {
            element.textContent = '获取失败';
            element.className = 'info-value error-message';
        });
    }

    // 更新设备信息
    function updateDeviceInfo(data) {
        const modelElement = document.getElementById('device-model');
        const snElement = document.getElementById('device-sn');

        modelElement.textContent = data.model || '--';
        modelElement.className = 'info-value'; // 清除加载状态CSS类

        snElement.textContent = data.SN || '--';
        snElement.className = 'info-value'; // 清除加载状态CSS类
    }

    // 更新版本信息
    function updateVersionInfo(data) {
        const hardwareElement = document.getElementById('hardware-version');
        const oemElement = document.getElementById('oem-version');
        const firmwareElement = document.getElementById('firmware-version');
        const sdkElement = document.getElementById('sdk-version');
        const softwareElement = document.getElementById('software-version');
        const otaElement = document.getElementById('ota-version');

        hardwareElement.textContent = data.hw_version || '--';
        hardwareElement.className = 'info-value'; // 清除加载状态CSS类

        oemElement.textContent = data.hw_ext_version || '--';
        oemElement.className = 'info-value'; // 清除加载状态CSS类

        firmwareElement.textContent = data.firmware || (data.sw_info && data.sw_info.firmware) || '--';
        firmwareElement.className = 'info-value';

        sdkElement.textContent = (data.sw_info && data.sw_info.sdk) || '--';
        sdkElement.className = 'info-value'; // 清除加载状态CSS类

        softwareElement.textContent = (data.sw_info && data.sw_info.arm) || '--';
        softwareElement.className = 'info-value'; // 清除加载状态CSS类

        otaElement.textContent = (data.sw_info && data.sw_info.ota) || '--';
        otaElement.className = 'info-value'; // 清除加载状态CSS类
    }

    // 更新系统状态
    function updateSystemStatus(data) {
        const storageElement = document.getElementById('storage-space');

        // 处理存储空间 - 服务端返回storage_free字段（单位：KB）
        if (data.storage_free !== undefined) {
            const free = data.storage_free || 0; // KB
            // 假设总空间，这里需要根据实际情况调整
            // 如果服务端有total字段，使用它；否则估算一个值
            const total = data.storage_total || (free + 1024 * 1024 * 10); // 假设总空间比可用空间多10GB
            const used = total - free; // 计算已使用空间
            const storagePercent = total > 0 ? ((used / total) * 100).toFixed(1) : 0;

            // 将KB转换为字节再格式化显示
            storageElement.textContent = `${formatStorageSimple(used * 1024)} / ${formatStorageSimple(total * 1024)} (${storagePercent}%)`;
            storageElement.className = `info-value ${storagePercent > 80 ? 'storage-low' : 'storage-normal'}`;
        } else {
            storageElement.textContent = '--';
            storageElement.className = 'info-value'; // 清除加载状态CSS类
        }
    }

    // 简化的存储格式化函数，保留一位小数
    function formatStorageSimple(bytes) {
        if (!bytes || bytes === 0) return '0B';

        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(1024));
        const value = bytes / Math.pow(1024, i);

        // 对于GB以上的单位，保留一位小数
        if (i >= 3) {
            return value.toFixed(1) + sizes[i];
        } else {
            return Math.round(value) + sizes[i];
        }
    }

    // 自动刷新设备信息
    // let autoRefreshInterval;

    function startAutoRefresh() {
        // 清除现有的定时器
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
        }

        // 每2秒自动刷新一次
        autoRefreshInterval = setInterval(() => {
            // 只有在设备信息页面激活时才刷新
            const deviceInfoPage = document.getElementById('device-info');
            if (deviceInfoPage.classList.contains('active')) {
                fetchDeviceInfo();
            }
        }, 2000);
    }

    // 页面加载时只初始化时间显示，不自动获取设备信息
    window.addEventListener('load', () => {
        // 立即显示当前时间
        updateCurrentTime();
        // 每秒更新时间显示
        setInterval(updateCurrentTime, 1000);

        // 不再自动触发设备信息获取，用户需要手动点击按钮
    });

    // 更新当前时间显示函数
    function updateCurrentTime() {
        const now = new Date();
        const timeString = now.getFullYear() + '-' +
                          String(now.getMonth() + 1).padStart(2, '0') + '-' +
                          String(now.getDate()).padStart(2, '0') + ' ' +
                          String(now.getHours()).padStart(2, '0') + ':' +
                          String(now.getMinutes()).padStart(2, '0') + ':' +
                          String(now.getSeconds()).padStart(2, '0');
        const timeElement = document.getElementById('current-time');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    // SN码设置逻辑
    /*document.getElementById('set-sn-btn').addEventListener('click', () => {
        const sn = document.getElementById('sn-input').value;
        const statusP = document.getElementById('sn-status');
        if (!sn) {
            statusP.textContent = 'SN码不能为空';
            return;
        }
        statusP.textContent = '正在设置...';
        fetch('/api/factory/set_SN', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({SN: sn})
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showTemporaryMessage(statusP, 'SN码设置成功！', 3000);
                } else {
                    statusP.textContent = '设置失败: ' + data.message;
                }
            })
            .catch(error => {
                statusP.textContent = '请求失败: ' + error;
            });
    });*/

    // 固件升级逻辑 (简化版)
    document.getElementById('start-upgrade-btn').addEventListener('click', async () => {
        const fileInput = document.getElementById('file-input');
        const statusP = document.getElementById('upgrade-status');
        const progressDiv = document.getElementById('upgrade-progress');

        if (fileInput.files.length === 0) {
            statusP.textContent = '请先选择文件';
            return;
        }

        const file = fileInput.files[0];
        statusP.textContent = '准备升级...';

        // 0. 计算文件MD5
        statusP.textContent = '正在计算文件MD5...';
        const fileMD5 = await calculateFileMD5(file);
        statusP.textContent = `文件MD5: ${fileMD5}.`;

        // 1. 开始升级请求
        let startResponse;
        try {
            const deviceInfo = await (await fetch('/api/info')).json();
            const startRes = await fetch('/api/upgrade/start', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    file_name: file.name,
                    file_size: file.size / 1024, // 转换为KB
                    model: deviceInfo.model,
                    md5: fileMD5
                })
            });
            startResponse = await startRes.json();
            if (startResponse.status !== 'ready') {
                throw new Error('服务器未准备好: ' + startResponse.message);
            }
            statusP.textContent = '服务器准备就绪，开始上传分片...';
        } catch (error) {
            statusP.textContent = '升级启动失败: ' + error.message;
            return;
        }

        // 2. 分片上传
        const chunkSize = 1 * 1024 * 1024; // 1MB
        const totalChunks = Math.ceil(file.size / chunkSize);
        let success = true;

        for (let i = 0; i < totalChunks; i++) {
            const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
            const chunkMD5 = SparkMD5.ArrayBuffer.hash(await chunk.arrayBuffer());

            const formData = new FormData();
            formData.append('chunk', i);
            formData.append('total', totalChunks);
            formData.append('file', chunk, file.name);
            // MD5sum on frontend can be slow, skipping for this example. Backend should handle it.
            formData.append('chunk_md5', chunkMD5);

            progressDiv.textContent = `正在上传分片 ${i + 1}/${totalChunks}`;

            try {
                const uploadRes = await fetch('/api/upgrade/upload', {
                    method: 'POST',
                    body: formData
                });
                const uploadResponse = await uploadRes.json();
                if (uploadResponse.status !== 'success') {
                    throw new Error(`分片 ${i} 上传失败: ` + (uploadResponse.message || '未知错误'));
                }
            } catch (error) {
                statusP.textContent = error.message;
                success = false;
                break;
            }
        }

        if (!success) {
            return;
        }
        progressDiv.textContent = '所有分片上传完毕。';
        statusP.textContent = '正在校验文件...';

        // 3. 检查文件
        try {
            // In a real scenario, you'd calculate the full file MD5 on the client.
            // const checkRes = await fetch(`/api/upgrade/check?file_size=${file.size}&md5=${fileMD5}`);
            const checkRes = await fetch(`/api/upgrade/check`);
            const checkResponse = await checkRes.json();
            if (checkResponse.status === 'success') {
                statusP.textContent = '文件校验成功！';
                progressDiv.textContent = '文件校验完成，等待用户确认升级。';

                // 显示确认对话框
                const confirmUpgrade = confirm(
                    '固件文件校验成功！\n\n' +
                    '是否确认开始升级？\n' +
                    '注意：升级过程中请勿断电，设备将会重启。'
                );

                if (confirmUpgrade) {
                    statusP.textContent = '用户已确认，正在执行升级...';
                    progressDiv.textContent = '正在执行升级操作...';
                    
                    // 4. 用户确认后执行升级
                    try {
                        const confirmRes = await fetch('/api/upgrade/confirm', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'}
                        });
                        const confirmResponse = await confirmRes.json();
                        
                        if (confirmResponse.status === 'success') {
                            statusP.textContent = '升级成功！设备即将重启...';
                            progressDiv.textContent = '升级完成，设备重启中...';
                        } else {
                            throw new Error('升级执行失败: ' + (confirmResponse.message || '未知错误'));
                        }
                    } catch (error) {
                        statusP.textContent = '升级执行失败: ' + error.message;
                        progressDiv.textContent = '升级失败，请重试。';
                    }
                } else {
                    // 用户取消升级，通知后端进行清理
                    statusP.textContent = '正在取消升级并清理文件...';
                    progressDiv.textContent = '正在清理升级文件...';
                    
                    try {
                        const cancelRes = await fetch('/api/upgrade/cancel', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'}
                        });
                        const cancelResponse = await cancelRes.json();
                        
                        if (cancelResponse.status === 'success') {
                            statusP.textContent = '用户取消升级操作，文件已清理。';
                            progressDiv.textContent = '升级已取消。如需升级，请重新上传固件文件。';
                        } else {
                            statusP.textContent = '取消升级失败: ' + (cancelResponse.message || '未知错误');
                            progressDiv.textContent = '清理文件时出现问题，请联系管理员。';
                        }
                    } catch (error) {
                        statusP.textContent = '取消升级请求失败: ' + error.message;
                        progressDiv.textContent = '无法通知服务器取消升级，请手动重试。';
                    }
                }
            } else {
                throw new Error('文件校验失败: ' + (checkResponse.message || '未知错误'));
            }
        } catch (error) {
            statusP.textContent = '校验请求失败: ' + error.message;
            progressDiv.textContent = '校验失败，请重试。';
        }
    });

    function calculateFileMD5(file) {
        return new Promise((resolve, reject) => {
            const chunkSize = 2097152; // Read in chunks of 2MB
            const chunks = Math.ceil(file.size / chunkSize);
            let currentChunk = 0;
            const spark = new SparkMD5.ArrayBuffer();
            const fileReader = new FileReader();

            fileReader.onload = (e) => {
                spark.append(e.target.result); // Append array buffer
                currentChunk++;

                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    const md5 = spark.end();
                    resolve(md5);
                }
            };

            fileReader.onerror = (e) => {
                reject(fileReader.error);
            };

            function loadNext() {
                const start = currentChunk * chunkSize;
                const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                fileReader.readAsArrayBuffer(file.slice(start, end));
            }

            loadNext();
        });
    }

    // 显示临时消息 duration ms 后自动消失
    function showTemporaryMessage(element, message, duration = 3000) {
        element.textContent = message;
        setTimeout(() => {
            element.textContent = '';
        }, duration);
    }

    // --- 日志查询逻辑 ---
    document.getElementById('fetch-logs-btn').addEventListener('click', fetchLogs);
    document.getElementById('log-level').addEventListener('change', filterLogs);

    let originalLogContent = ''; // 存储原始日志以便筛选

    function fetchLogs() {
        const logDisplayPre = document.querySelector('#log-display pre');
        logDisplayPre.textContent = '正在获取日志...';

        fetch('/api/check/app_log')
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => { throw new Error(err.message || `HTTP error ${response.status}`); });
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    originalLogContent = data.logs || '日志内容为空。';
                    // 直接更新DOM，然后应用过滤器
                    logDisplayPre.textContent = originalLogContent;
                    filterLogs(); // 获取后立即应用当前过滤器
                } else {
                    originalLogContent = `获取日志失败: ${data.message}`;
                    logDisplayPre.textContent = originalLogContent;
                }
            })
            .catch(error => {
                console.error('获取日志失败:', error);
                originalLogContent = `获取日志失败: ${error.message}`;
                logDisplayPre.textContent = originalLogContent;
            });
    }

    function filterLogs() {
        const logLevel = document.getElementById('log-level').value;
        const logDisplayPre = document.querySelector('#log-display pre');

        if (!originalLogContent || originalLogContent.startsWith('获取日志失败')) {
            logDisplayPre.textContent = originalLogContent;
            return;
        }

        if (logLevel === 'all') {
            logDisplayPre.textContent = originalLogContent;
            return;
        }

        const lines = originalLogContent.split('\n');
        const filteredLines = lines.filter(line => {
            // 匹配类似 "[info]" 或 "[error]" 的日志级别
            const match = line.match(/\[(info|warning|error|debug|trace|critical)\]/i);
            return match && match[1].toLowerCase() === logLevel;
        });

        logDisplayPre.textContent = filteredLines.length > 0 ? filteredLines.join('\n') : `没有找到级别为 "${logLevel}" 的日志。`;
    }


    // 日志页面 (前端模拟)
    document.getElementById('export-logs-btn').addEventListener('click', () => {
        const logContent = document.querySelector('#log-display pre').innerText;
        const blob = new Blob([logContent], {type: 'text/plain'});
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = 'device-logs.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    });

    // 设备配置选项卡切换
    function showConfigSection(sectionId) {
        const sections = document.querySelectorAll('.config-content');
        const tabs = document.querySelectorAll('.config-tab');

        sections.forEach(section => {
            section.classList.remove('active');
        });
        tabs.forEach(tab => {
            tab.classList.remove('active');
        });

        document.getElementById(sectionId).classList.add('active');

        // 正确地激活对应的选项卡
        tabs.forEach(tab => {
            if ((sectionId === 'param-config' && tab.textContent.trim() === '参数配置') ||
                (sectionId === 'system-config' && tab.textContent.trim() === '系统设置')) {
                tab.classList.add('active');
            }
        });
    }

    // 更新当前时间显示
    function updateCurrentTime() {
        const now = new Date();
        const timeString = now.getFullYear() + '-' +
                          String(now.getMonth() + 1).padStart(2, '0') + '-' +
                          String(now.getDate()).padStart(2, '0') + ' ' +
                          String(now.getHours()).padStart(2, '0') + ':' +
                          String(now.getMinutes()).padStart(2, '0') + ':' +
                          String(now.getSeconds()).padStart(2, '0');
        const timeElement = document.getElementById('current-time');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    // 每秒更新时间显示
    setInterval(updateCurrentTime, 1000);
    updateCurrentTime(); // 立即显示一次

    // 时间同步逻辑
    document.getElementById('sync-time-btn').addEventListener('click', () => {
        const statusP = document.getElementById('time-sync-status');
        const currentTime = new Date();

        statusP.textContent = '正在同步系统时间到设备...';
        fetch('/api/system/sync_time', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                timestamp: Math.floor(currentTime.getTime() / 1000),
                timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                showTemporaryMessage(statusP, '系统时间同步成功！', 3000);
            } else {
                statusP.textContent = '时间同步失败: ' + data.message;
            }
        })
        .catch(error => {
            statusP.textContent = '请求失败: ' + error;
        });
    });

    // 系统重启逻辑
    document.getElementById('reboot-btn').addEventListener('click', () => {
        if (!confirm('确定要重启设备吗？重启后需要重新连接。')) {
            return;
        }

        const statusP = document.getElementById('reboot-status');
        statusP.textContent = '正在重启设备...';

        fetch('/api/system/reboot', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                statusP.textContent = '设备正在重启，请稍后重新连接...';
            } else {
                statusP.textContent = '重启失败: ' + data.message;
            }
        })
        .catch(error => {
            statusP.textContent = '请求失败: ' + error;
        });
    });

    // 恢复出厂设置逻辑
    document.getElementById('factory-reset-btn').addEventListener('click', () => {
        if (!confirm('确定要恢复出厂设置吗？这将清除所有配置数据！')) {
            return;
        }
        if (!confirm('此操作不可撤销，确认继续吗？')) {
            return;
        }

        const statusP = document.getElementById('factory-reset-status');
        statusP.textContent = '正在恢复出厂设置...';

        fetch('/api/system/factory_reset', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'}
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                statusP.textContent = '出厂设置恢复成功！设备将重启...';
            } else {
                statusP.textContent = '恢复失败: ' + data.message;
            }
        })
        .catch(error => {
            statusP.textContent = '请求失败: ' + error;
        });
    });
``
    // 保存设备基本信息设置
    document.getElementById('save-device-info-btn').addEventListener('click', () => {
        const sn = document.getElementById('sn-input').value;
        const model = document.getElementById('model-input').value;
        const hwVersion = document.getElementById('hw-version-input').value;
        const hwExtVersion = document.getElementById('oem-version-input').value;
        const statusP = document.getElementById('device-info-status');

        // 简单验证
        if (!sn || !model || !hwVersion || !hwExtVersion) {
            statusP.textContent = '所有字段都是必填的';
            return;
        }

        statusP.textContent = '正在保存设备信息...';
        fetch('/api/factory/set_device_info', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                SN: sn,
                model: model,
                hw_version: hwVersion,
                hw_ext_version: hwExtVersion
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                showTemporaryMessage(statusP, '设备信息保存成功！', 3000);
                // 更新设备信息卡片
                updateDeviceInfo({model, SN: sn});
                updateVersionInfo({hw_version: hwVersion, hw_ext_version: hwExtVersion});
            } else {
                statusP.textContent = '保存失败: ' + data.message;
            }
        })
        .catch(error => {
            statusP.textContent = '请求失败: ' + error;
        });
    });

    // 获取当前设备信息并填充到表单
    document.getElementById('get-current-info-btn').addEventListener('click', () => {
        const statusP = document.getElementById('device-info-status');
        statusP.textContent = '正在获取当前设备信息...';

        fetch('/api/info')
            .then(response => response.json())
            .then(data => {
                if (data) {
                    document.getElementById('sn-input').value = data.SN || '';
                    document.getElementById('model-input').value = data.model || '';
                    document.getElementById('hw-version-input').value = data.hw_version || '';
                    document.getElementById('oem-version-input').value = data.hw_ext_version || '';
                    statusP.textContent = '设备信息已加载';
                } else {
                    statusP.textContent = '未能获取设备信息';
                }
            })
            .catch(error => {
                statusP.textContent = '请求失败: ' + error;
            });
    });

    // 自动获取设备信息并填充到参数配置表单
    function autoLoadDeviceInfoToForm() {
        const statusP = document.getElementById('device-info-status');
        statusP.textContent = '正在自动获取设备信息...';

        fetch('/api/info')
            .then(response => response.json())
            .then(data => {
                if (data) {
                    // 填充表单字段
                    document.getElementById('sn-input').value = data.SN || '';
                    document.getElementById('model-input').value = data.model || '';
                    document.getElementById('hw-version-input').value = data.hw_version || '';
                    document.getElementById('oem-version-input').value = data.hw_ext_version || '';

                    // 显示成功状态，3秒后自动清除
                    showTemporaryMessage(statusP, '设备信息已自动加载', 3000);
                } else {
                    statusP.textContent = '未能获取设备信息';
                }
            })
            .catch(error => {
                statusP.textContent = '自动获取失败: ' + error;
            });
    }
</script>

</body>
</html>
